/*
 * 文件操作，包括读写，上传下载等
 */
var FileOperator = {
	fileTransfer: null,
	hasInit: false,
	audioFileRoot: '',
	checkDownFileExists: false,
	uploadUrl: '',//上传路径
	mode: null,
	/*内部属性*/
	options: {},
	//初始化
	init: function(){
		if(this.hasInit){
			return;
		}
		if(!this.mode){
			this.mode = GLOBALFUN_getMode();
		}
		//根据是否phoneGap应用决定采取哪种方式的fileTransfer
		if(this.mode=="phoneGap"){			
			this.fileTransfer = new FileTransfer();	
			this.pictureSource = navigator.camera.PictureSourceType;
			this.destinationType = navigator.camera.DestinationType;
		}else{		
			this.fileTransfer = $.extend({},FileTransferWeb,{});
		}	
		this.hasInit = true;
	},
	/*
	 * 上传文件
	 * @param filePath 文件全路径
	 * @param remoteUrl 服务器上传地址
	 * @param params 其他参数
	 * @param sucCallback 上传成功后的回调
	 * @param failCallback 上传失败后的回调
	 * @param processCallback 进度回调
	 */
	uploadFile: function(filePath,remoteUrl,params,sucCallback,failCallback,processCallback){	
		this.init();	
		var _self = this;
        //数据类型
        if(params.mimeType){
        	this.options.mimeType = params.mimeType;
        }else{
        	this.options.mimeType = "multipart/form-data";
        }
        var fileName = null;
        //如果参数中有文件名，则用参数中的，否则用路径中的
        if(params.fileName&&params.fileName.length>0){
        	fileName = params.fileName;
        }else{
	        var sp =  filePath.split("/");   
	        var fileName = sp[sp.length-1];	   
	        console.log("fileName after sps:" + fileName);     
        }      
        this.options.fileName = fileName;
		for (var p in params) {
			this.options[p] = params[p];
		}       
        console.log("filePath is:" + filePath + " and fileName:" + fileName); 
        var tryTime = 0;
        var uploadAction = null;
        var failUpload = function(err){
           	console.log("upload fail:" + err.code);
        	tryTime++;
        	if(tryTime>2){
        		console.log("more fail,quit");	
        	}else{
        		//try one more time
        		console.log("try again");	
        		uploadAction.call();
        	}         	
        };        
        var opt = this.options;
        if(this.mode=="phoneGap"){
        	opt = new FileUploadOptions();
        	opt.params = this.options;
        	opt.type = this.options.type;
        	opt.fileKey = this.options.fileKey;
        	opt.fileName = this.options.fileName;
        	opt.mimeType = this.options.mimeType;
        	console.log("opt is:" + JSON.stringify(opt));
        }       
        uploadAction = function(fileRealPath){  
        	console.log("upload file,fileRealPath:" + fileRealPath + " and url:" + remoteUrl);     	
	        _self.fileTransfer.upload(fileRealPath, encodeURI(remoteUrl), function(res){
	        	var resText;
	        	if(_self.mode=="phoneGap"){
	        		resText = res.response;
	        	}else{
	        		resText = res;
	        	}
	        	console.log("trans suc,resText:" + resText);
	        	if(sucCallback){
	        		sucCallback(resText);
	        	}	        	
	        }, function(e){
	        	console.log("upload fail:" + JSON.stringify(e));
	        	if(failCallback){	        		
	        		failCallback(e);
	        	}		        	
	        }, opt);          	   	
        };
        if(this.mode=="phoneGap"){
			//phoneGap模式读取文件并上传
			this.isFileExists(filePath,  function(fileEntry) {
				uploadAction(fileEntry.toURL());	
			}, function(e){
				console.log("get file fail:" + e.code + " with file:" + filePath);
			});	 
		}else{
			//web模式直接使用filePath
			uploadAction(filePath);
		}		        
		
	},
	//下载文件
	downloadFile: function(remoteUrl,filePath,downloadSuccess,downloadFail,flag,options){
		var _self = this;	
		this.init();		 
        console.log("download remoteUrl isss:" + remoteUrl + " and filePath is:" + filePath); 
        console.log("options is:",options);
        if(this.mode=="phoneGap"){
			//先创建相关目录，再进行拷贝
			var parentDir = filePath.substring(0,filePath.lastIndexOf('/'));	
			this.createDir(parentDir,function(){
				filePath = GLOABAL_SYSTEMROOT_ABS + "/" + filePath;
				console.log("filePath in p:" + filePath);
				_self.fileTransfer.download(encodeURI(remoteUrl),filePath,downloadSuccess,downloadFail,false,options);				
			}); 
			return;
		}       
        this.fileTransfer.download(encodeURI(remoteUrl),filePath,downloadSuccess,downloadFail,false,options);
	},	
	//数据写入文件
	writeDataToFile: function(data,filePath,options){
		if(this.mode=="native"){
			var path = filePath.substring(0,filePath.lastIndexOf("/"));
			console.log("path is:" + path + " and filePath:" + filePath);
			//先创建目录,回调模式调用写文件操作
			this.createDir(path,function(){
				MAIN_fileSystem.getFile(filePath, {
					create : true,
					exclusive : false
				}, function(fileEntry) {
					console.log("get file with write:" ,fileEntry);
					fileEntry.createWriter(function(fileWriter) {
						fileWriter.onwriteend = function(e) {
							if(options.callback){
								options.callback(fileEntry);
							}							
						};
						fileWriter.write(data);
					}, options.failAction);
				}, function(e){
					console.log("get file fail with write:" ,e);
				}); 				
			});				
		}
	},
	//创建目录(多层)
	createDir: function(path,endCall){
		var folders = path.split('/');
		if(this.mode=="native"){			
			this.createDirInner(MAIN_fileSystem,folders,endCall);			
		}else{
			this.createDirInnerPhone(MAIN_fileSystem,path,endCall);
		}
	},
	createDirInner: function(rootDirEntry, folders,endCall){
		var _self = this;
		if (folders[0] == '.' || folders[0] == '') {
			folders = folders.slice(1);
		}
		console.log("create folder:" + folders + " and rootDirEntry:" , rootDirEntry);
		rootDirEntry.getDirectory(folders[0], {
			create : true
		}, function(dirEntry) {			
			if (folders.length) {
				_self.createDirInner(dirEntry, folders.slice(1),endCall);
			}else{
				endCall();
			}
		}, function(e){
			console.log("createDirInner error",e);
		}); 	
	},	
	createDirInnerPhone: function(rootDirEntry, path,endCall){
		var dirs = path.split("/").reverse();
		var root = rootDirEntry;		
		var createDir = function(dir){
			console.log("create dir " + dir);
			root.getDirectory(dir, {
				create : true,
				exclusive : false
			}, successCB, failCB);
		};		
		var successCB = function(entry){
			console.log("dir created " + entry.fullPath);
			root = entry;
			if(dirs.length > 0){
				createDir(dirs.pop());
			}else{
				console.log("all dir created");
				endCall(entry);
			}
		};		
		var failCB = function(){
			console.log("failed to create dir " + dir);
		};
		createDir(dirs.pop());	
	},		
	/*
	 * 回调模式检查文件是否存在
	 */
	isFileExists: function(fileFullPath,yesCallback,noCallback){
		this.init();
		if(this.mode=="phoneGap"){				
			if(fileFullPath.indexOf("/")==0){
				fileFullPath = fileFullPath.substring(1,fileFullPath.length);
			}
			if(fileFullPath.indexOf("/")!=0){
				//fileFullPath = "/" + fileFullPath;
			}			
			console.log("fileFullPath iss:" + fileFullPath);
			MAIN_fileSystem.getFile(fileFullPath,{create: false, exclusive: true},function(fileEntry){
				console.log("file exits,url:" + fileEntry.toURL());
				yesCallback(fileEntry);
			},function(evt){
				console.log("file not exits,file:" + fileFullPath + " and code:" + evt.code);
				noCallback(evt);
			});	
		}else{	
			console.log("fileFullPath is:" + fileFullPath);
			MAIN_fileSystem.getFile(fileFullPath,{create: false, exclusive: false},function(fileEntry){
				console.log("file exits,url:" + fileEntry.toURL());			
				yesCallback(fileEntry);
			},function(evt){
				console.log("file not exits:" , evt);
				noCallback();
			});
		}	
	},
	//拷贝文件
	copyFile: function(oriFilePath,tarFilePath,sucCallback){
		var _self = this;
		console.log("copyFile in,oriFilePath:" + oriFilePath + " and tarFilePath:" + tarFilePath);
		if(this.mode=="phoneGap"){
			if(oriFilePath.indexOf("/")==0){
				oriFilePath = oriFilePath.substring(1,oriFilePath.length);
			}			
			if(tarFilePath.indexOf("/")==0){
				tarFilePath = tarFilePath.substring(1,tarFilePath.length);
			}								
			var parentDir = tarFilePath.substring(0,tarFilePath.lastIndexOf('/'));	
			if(parentDir.indexOf("/")==0){
				parentDir = parentDir.substring(1,parentDir.length);
			}				
			var fileName = tarFilePath.substring(tarFilePath.lastIndexOf('/')+1);	
			console.log("parentDir is:" + parentDir + " and fileName:" + fileName);
			//先创建相关目录，再进行拷贝
			this.createDir(parentDir,function(){
				MAIN_fileSystem.getFile(oriFilePath, {
					create : false,
					exclusive : false
				}, function(entry) {
					MAIN_fileSystem.getDirectory(parentDir, {create: true},function(targetEntry){
						console.log("get dir suc");
						entry.copyTo(targetEntry, fileName, function(tarEntry) {
							console.log("copy file success");
							sucCallback(tarEntry);
						}, function(evt) {
							console.log("copy file fail:" + evt.code);
						});					
					},function(evt){
						console.log("get dir iss fail:" + evt.code);
					});
				}, function(evt) {
					console.log("file not exits:" + evt.code);
				});					
			});
			return;
		}		
		//通过文件系统进行回调式的文件拷贝
		MAIN_fileSystem.getFile(oriFilePath, {
			create : false,
			exclusive : false
		}, function(entry) {
			var parentDir = tarFilePath.substring(0,tarFilePath.lastIndexOf('/'));
			console.log("parentDir is:" + parentDir);
			//首先创建目录
			_self.createDir(parentDir,function(){
				var fileName = tarFilePath.substring(tarFilePath.lastIndexOf('/')+1);
				MAIN_fileSystem.getDirectory(parentDir,{create : true,exclusive : false},
					function(tarEntry){
						console.log("getDirectory ok:" , tarEntry);
						entry.copyTo(tarEntry, fileName, function(){
							console.log("copy file success");
							sucCallback(tarEntry);
						}, function(evt){
							console.log("copy file fail:" , evt);
						});				
					},
					function(evt){console.log("get target path fail:" , evt);}
				);				
			});

		}, function(evt) {
			console.log("file not exits:" + evt.code);
		});		
	}	
};


